/**
 * created by 小卷毛, 2020-05-06 006
 * Copyright (c) 2020, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.aifeng.viewmodel

import androidx.lifecycle.MutableLiveData
import com.aifeng.common_ui.helper.formatDecimal
import com.aifeng.common_ui.helper.toNotDouble
import com.aifeng.common_ui.helper.toNotInt
import com.aifeng.model.BaseUrl
import com.aifeng.model.CommonData
import com.aifeng.model.CommonModel
import com.aifeng.model.GoodsModel
import com.aifeng.utils.applyFlowableSchedulers
import com.aifeng.utils.applySchedulers
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import io.reactivex.Flowable
import org.json.JSONArray
import org.json.JSONObject

/**
 * 项目名称：Hassan_Food
 * 创建人：小卷毛
 * 创建时间：2020-05-06 16:00
 */
class GoodsViewModel : BaseViewModel() {

    val resultEvent = MutableLiveData<List<String>>()

    fun getGoodsType() =
        OkGo.post<BaseResponse<GoodsModel>>(BaseUrl.goodsType)
            .converter(object : JsonConvert<BaseResponse<GoodsModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }

    fun getGoodsList(
        page: Int,
        id: String = "",
        name: String = ""
    ) =
        OkGo.post<BaseResponse<GoodsModel>>(BaseUrl.goodsList)
            .params(
                getParams(
                    "page" to page,
                    "goodstype" to id,
                    "search" to name
                )
            )
            .converter(object : JsonConvert<BaseResponse<GoodsModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.results }

    fun getDetail(id: String) =
        OkGo.post<BaseResponse<CommonData>>(BaseUrl.goodsDetail)
            .params(getParams("id" to id))
            .converter(object : JacksonConvert<BaseResponse<CommonData>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }
            .map { it.data }

    fun getRecommendList(userId: String) =
        OkGo.post<BaseResponse<ArrayList<CommonData>>>(BaseUrl.goodsRecommend)
            .params(getParams("userid" to userId))
            .converter(object : JacksonConvert<BaseResponse<ArrayList<CommonData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }

    fun getCarList(id: String) =
        OkGo.post<BaseResponse<CommonModel>>(BaseUrl.carList)
            .params(getParams("userid" to id))
            .converter(object : JacksonConvert<BaseResponse<CommonModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.results }

    fun addToCar(
        id: String,
        userId: String,
        num: Int
    ) =
        RxSingleHelper.requestString(
            url = BaseUrl.addCar,
            params = getParams(
                "goodsid" to id,
                "userid" to userId,
                "num" to num
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun deleteCar(id: String, userId: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.delCar,
            params = getParams(
                "userid" to userId,
                "id" to id
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun clearCar(userId: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.delCar,
            params = getParams("userid" to userId)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun calculateTotal(items: ArrayList<CommonData>) {
        mDisposables.add(
            Flowable.just(items)
                .map { data ->
                    val list = ArrayList<String>()

                    if (data.any { it.isChecked }) {
                        var priceTotal = 0.0
                        var orginTotal = 0.0
                        data.filter { it.isChecked }.forEach {
                            priceTotal += it.price.toNotDouble() * it.num.toNotInt()
                            orginTotal += it.orgprice.toNotDouble() * it.num.toNotInt()
                        }

                        list.add(priceTotal.formatDecimal())
                        list.add(orginTotal.formatDecimal())
                        list.add(data.filter { it.isChecked }.size.toString())
                    }

                    return@map list
                }
                .compose(applyFlowableSchedulers())
                .subscribe { resultEvent.value = it }
        )
    }

    fun getCheckJson(
        items: ArrayList<CommonData>,
        onResult: (String) -> Unit
    ) {
        if (items.none { it.isChecked }) {
            showToast("请选择要结算的商品！")
            return
        }

        if (items.filter { it.isChecked }
                .none { it.specstype == "package" }
        ) {
            var totalNum = 0
            items.filter { it.isChecked }
                .forEach {
                    totalNum += it.num.toNotInt()
                }
            if (totalNum < 6) {
                showToast("非套餐类商品至少购满6件才可结算！")
                return
            }
        }

        mDisposables.add(
            Flowable.just(items)
                .map {
                    val jsonArray = JSONArray()
                    items.filter { it.isChecked }.forEach {
                        jsonArray.put(JSONObject().apply {
                            put("goodsid", it.goodsid)
                            put("num", it.num)
                        })
                    }
                    return@map jsonArray.toString()
                }
                .compose(applyFlowableSchedulers())
                .subscribe { onResult.invoke(it) }
        )
    }

}